package org.easyx.ui.util;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.easyx.core.entity.Constants;
import org.easyx.core.utils.ObjKit;
import org.easyx.ser.sys.entity.SysResource;
import org.easyx.ser.sys.entity.SysUser;
import org.easyx.ser.sys.entity.SysUserRole;
import org.easyx.ser.sys.serivce.SysResourceService;
import org.easyx.ser.sys.serivce.SysUserRoleService;
import org.easyx.ui.base.BossEasyUISessionUser;

public class SessionKit {
	/**
	 * 获取当前登录用户
	 */
	public static BossEasyUISessionUser getSessionUser(HttpServletRequest request){
		if(request == null){
			return null;
		}
		return (BossEasyUISessionUser) request.getSession().getAttribute(Constants.SESSION_USER);
	}
	
	/**
	 * 添加当前登录用户到session中
	 * 
	 * @param request
	 * @param sessionUser
	 * @return
	 */
	public static BossEasyUISessionUser setSessionUser(HttpServletRequest request,BossEasyUISessionUser sessionUser){
		if(request == null){
			throw new IllegalArgumentException("HttpServletRequest不能为空");
		}
		request.getSession().setAttribute(Constants.SESSION_USER, sessionUser);
		return sessionUser;
	}
	
	/**
	 * 构建SessionUser 
	 * @param user
	 * @param request
	 * @param userRoleService
	 * @param sysResourceService
	 * @return
	 */
	public static BossEasyUISessionUser genSessionUserByUser(SysUser user, SysUserRoleService userRoleService,
			SysResourceService sysResourceService) {
		// 读取用户的url和角色
		Set<String> roles = new HashSet<String>();
		List<SysUserRole> sur = userRoleService.selectAllByUserId(user.getId());
		if(sur!=null && sur.size()>0){
			for(SysUserRole r : sur){
				roles.add(r.getRoleId()+"");
			}
		}
		
		List<SysResource> resList = sysResourceService.selectListByUserId(user.getId(),null);
		Set<String> urls = new HashSet<String>();
		for(SysResource re: resList){
			if(ObjKit.isNotEmpty(re.getUrl())){
				urls.add(re.getUrl());
			}
		}
		
		BossEasyUISessionUser su = new BossEasyUISessionUser();
		su.setRoleIds(roles);
		su.setUrls(urls);
		su.setLoginName(user.getLoginName());
		su.setRealName(user.getRealName());
		su.setUserId(user.getId());
//		su.setIp(WebUtil.getIpAddress(request));
		
		return su;
	}
}
